package com.aviccxzx.smarthome.UserModule;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.BaseActivity;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.NetUtils;
import com.aviccxzx.smarthome.video.CloudUtil;
import com.jovision.AppConsts;
import com.jovision.CommonUtil;
import com.jovision.JVNetConst;
import com.jovision.JniUtil;
import com.jovision.sovplay.SovUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;

import static com.larksmart7618.sdk.communication.tools.controlswitch.FuncSwitch.TAG;


/**
 * Created by joey on 2016/10/25.
 */
public class SmartLinkActivity1 extends BaseActivity implements View.OnClickListener {

    static {
        System.loadLibrary("gnustl_shared");
        System.loadLibrary("stlport_shared");
        System.loadLibrary("tools");
        System.loadLibrary("nplayer");
        System.loadLibrary("alu");
        System.loadLibrary("play");
    }

    EditText content;//定义一个文本输入框
    private Dialog dialog;
    String name, pwd;
    private byte mAuthMode;
    private byte AuthModeWPA = 0x03;
    private ArrayList<Map<String, String>> broadStrList = null;
    private SimpleAdapter adapter;
    private ListView broadListView;
    Timer timer;
    Animation rotateAnim;
    private ImageView radar_scan_img;
    boolean hasSearched;
    RelativeLayout card;
    LinearLayout wave_add_ll;
    Button send_cancle;
    TextView send_wave;
    /**
     * 存储器
     */
    public SharedPreferences spf;
    /**
     * 存储器默认名称
     */
    public static final String SPF_Name = "set";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSettings();
        initUi();
    }

    @Override
    public void onHandler(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            //云视通纯局域网广播回调 0xAE
            case JVNetConst.CALL_LOCAL_LAN_DEVICE: {
                break;
            }
            //云视通全网段广播回调 0xA8
            case JVNetConst.CALL_LAN_SEARCH_SERVER: {
                break;
            }

            //猫眼局域网广播回调 0xD9
            case JVNetConst.CALL_CAT_BROAD_CALLBACK: {
                if (!hasSearched) {
                    analysisStreamData(obj.toString());
                }
                break;
            }
        }
    }

    @Override
    protected void initSettings() {
        JniUtil.initElian();
        CloudUtil.startLanSearchServer(CommonUtil.getLocalIpAddress());
        CommonUtil.createDirectory(AppConsts.LOG_PATH);
        CommonUtil.createDirectory(AppConsts.CAPTURE_PATH);
        CommonUtil.createDirectory(AppConsts.VIDEO_PATH);
        CommonUtil.createDirectory(AppConsts.DOWNLOAD_PATH);
    }

    @Override
    protected void initUi() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.smart_link1);
        } else {
        }
        //初始化摄像头SDK
        try {
            JniUtil.initSDK(getApplication(), AppConsts.LOG_PATH, "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        findViewById(R.id.send_cancle).setOnClickListener(this);
        findViewById(R.id.send_wave).setOnClickListener(this);
        findViewById(R.id.send_wave_next).setOnClickListener(this);
        name = getIntent().getStringExtra("wifiname");
        pwd = getIntent().getStringExtra("wifipwd");
        broadStrList = new ArrayList<>();

        card = (RelativeLayout) findViewById(R.id.card);
        wave_add_ll = (LinearLayout) findViewById(R.id.wave_add_ll);
        send_cancle = (Button) findViewById(R.id.send_cancle);
        send_wave = (TextView) findViewById(R.id.send_wave);
        ((TextView) findViewById(R.id.title_tv)).setText("搜索设备");
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        radar_scan_img = (ImageView) findViewById(R.id.radar_scan_img);
        spf = getSharedPreferences(SPF_Name, Context.MODE_PRIVATE);
        String type = spf.getString("type", "");
        if (type.equals("cat")) {
            //猫眼相机是就声波发送
            //把媒体音量调最大
            card.setVisibility(View.GONE);
            wave_add_ll.setVisibility(View.VISIBLE);
            AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,maxVolume , 0);
        } else {
            card.setVisibility(View.VISIBLE);
            wave_add_ll.setVisibility(View.GONE);
            setRotate();
            send();
        }
        closeAddCam();
    }


    Timer mtimer = null;
    Timer textChangetimer = null;

    public void closeAddCam() {
        if (mtimer == null) {
            mtimer = new Timer();
        }
        mtimer.schedule(new TimerTask() {
            int i = 150;

            @Override
            public void run() {
                i--;
                if (i == 0) {
                    Looper.prepare();
                    App.getApp().showToast("添加失败");
                    mtimer.cancel();
                    mtimer = null;
                    App.getApp().quit();
                    SmartLinkActivity1.this.finish();
                    Looper.loop();
                }
            }
        }, 0, 1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mtimer != null) {
            mtimer.cancel();
            mtimer = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void setRotate() {
        // 加载动画
        rotateAnim = AnimationUtils.loadAnimation(this, R.anim.radar_rotate);
        LinearInterpolator lin = new LinearInterpolator();// 匀速旋转
        rotateAnim.setInterpolator(lin);
        radar_scan_img.startAnimation(rotateAnim);
    }

    @Override
    protected void saveSettings() {

    }

    @Override
    protected void freeMe() {
        CloudUtil.stopLanSearchServer();
    }

    /**
     * 解析流媒体协议的回调数据
     *
     * @param jsonStr
     */
    public void analysisStreamData(String jsonStr) {
        //        "privateinfo":"hipc","timeout":2,"ystno":"H30281117"}
        //obj={"privateinfo":"hipc","timeout":2,"ystno":"H30281117"}
        try {
            JSONObject broadJson = new JSONObject(jsonStr);
            String ystNum = broadJson.getString("ystno");
            String yst = spf.getString("yst", "");
            if ("0" != ystNum) {
                if (!TextUtils.isEmpty(yst) && ystNum.equals(yst)) {
                    //添加到机智云后台
                    hasSearched = true;
                    bindCam(ystNum);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void bindCam(final String yst) {
        String phone_imei = NetUtils.getIMEI(SmartLinkActivity1.this);
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        boolean standard = spf.getBoolean("standard", false);
        int configure;
        if (standard) {
            configure = 0;
        } else {
            configure = 1;
        }
        Call<ResponseBody> call = service.bindCam(yst, "admin", "admin", phone_imei, configure);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                //在服务器绑定成功

                //1.添加设备到中维服务器上
                String[] ystArray = {yst};
                SovUtil.addYSTNOS(ystArray);
                MsgCenter.fireNull("yst", yst);
                App.getApp().quit();
                finish();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.toString();
                App.getApp().showToast("添加失败");
                App.getApp().quit();
                finish();
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.send_cancle:
                JniUtil.stopElian();
                finish();
                break;
            case R.id.send_wave:
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        //进行 耗时操作
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String param = String.format(AppConsts.SOUND_WAVE_FORMATTER, name, pwd);
                                JniUtil.newSendSoundWave(param, Integer.parseInt("6"));
                            }
                        });
                    }
                }.start();

                send_wave.setText("声波发送中");
                send_wave.setClickable(false);
                if (textChangetimer == null) {
                    textChangetimer = new Timer();
                }
                textChangetimer.schedule(new TimerTask() {
                    int i = 7;

                    @Override
                    public void run() {
                        i--;
                        if (i == 0) {
                            send_wave.post(new Runnable() {
                                @Override
                                public void run() {
                                    send_wave.setText("发送声波");
                                    send_wave.setClickable(true);
                                }
                            });
                        }
                    }
                }, 0, 1000);

                break;
            case R.id.send_wave_next:
                broadStrList.clear();
                if (null != adapter) {
                    adapter.notifyDataSetChanged();
                }
                //猫眼局域网广播回调 0xB7
                //                SovUtil.searchLanDev();

                timer = new Timer();
                timer.schedule(new TimerTask() {
                    int i = 20;

                    @Override
                    public void run() {
                        i--;
                        //流媒体局域网广播回调 0xB7
                        if (timer != null) {
                            SovUtil.searchLanDev();
                        }
                        if (i == 0 && timer != null) {
                            timer.cancel();
                        }
                    }
                }, 0, 3000);

                card.setVisibility(View.VISIBLE);
                wave_add_ll.setVisibility(View.GONE);
                send_cancle.setVisibility(View.GONE);
                setRotate();
                break;
        }
    }

    /**
     * 发送命令
     */
    public void send() {
        mAuthMode = AuthModeWPA;
        JniUtil.sendElian(name, pwd, mAuthMode);
        broadStrList.clear();
        if (null != adapter) {
            adapter.notifyDataSetChanged();
        }

        timer = new Timer();
        timer.schedule(new TimerTask() {
            int i = 20;

            @Override
            public void run() {
                i--;
                //流媒体局域网广播回调 0xB7
                if (timer != null) {
                    SovUtil.searchLanDev();
                }
                if (i == 0 && timer != null) {
                    timer.cancel();
                }
            }
        }, 0, 3000);
    }

    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj) {
        Log.e(TAG, "onNotify:what=" + what + ";arg1=" + arg1 + ";arg2=" + arg2 + ";obj=" + obj);
        //已经搜索到设备
        handler.sendMessage(handler.obtainMessage(what, arg1, arg2, obj));
        JniUtil.stopElian();
    }
}
